<?php
/**
 * 编辑器图片上传
 * User: dxk
 * Date: 2016/12/21
 */
namespace App\Library\Service;
class Ueditor
{
    private $folder = 'editor';//目标文件夹
    private $show_image_suffix = '_1000x30000.jpg';//目标文件夹
    private $CONFIG;

    public function __construct()
    {
        set_time_limit(0);
    }

    /**
     * 目标文件夹
     * @param $folder
     * @return $this
     */
    public function setFolder($folder)
    {
        $this->folder = strtolower(trim($folder));
        return $this;
    }

    /**
     * 要展示的图片规格
     * @param $show_image_size
     * @return $this
     */
    public function setShowImageSize($show_image_size)
    {
        $pic_size = config('sys.pic_size');
        if (in_array($show_image_size, $pic_size)) {
            $this->show_image_suffix = '_' . $show_image_size . '.jpg';
        }
        return $this;
    }

    public function dispatch()
    {
        $config_content = \Cache::get('ueditor');
        if (empty($config_content)) {
//            $config_content = file_get_contents(easy_asset("vendor/ueditor/php/config.json"));
            $config_content = file_get_contents(public_path('resource/vendor/ueditor/php/config.json'));
            $config_content = preg_replace('/\/\*[\s\S]+?\*\//', "", $config_content);
            if (!empty($config_content)) {
                \Cache::put('ueditor', $config_content, 60);
            }
        }
        $CONFIG = json_decode($config_content, true);
        $this->CONFIG = $CONFIG;
        $action = trim($_GET['action']);
        // 获取图片的尺寸
        switch ($action) {
            case 'config':
                $result = json_encode($CONFIG);
                break;
            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->upload();
                break;
            /* 列出图片 */
            case 'listimage':
                $result = json_encode(['state' => '不支持此功能']);
                break;
            /* 列出文件 */
            case 'listfile':
                $result = '';
                break;
            /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->crawler();
                break;
            default:
                $result = json_encode(['state' => '请求地址出错']);
                break;
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(['state' => 'callback参数不合法']);
            }
        } else {
            echo $result;
        }
        exit();
    }


    /**
     * 抓取远程图片
     * @return string
     */
    protected function crawler()
    {
        /* 上传配置 */
        $config = array(
            "pathFormat" => $this->CONFIG['catcherPathFormat'],
            "maxSize" => $this->CONFIG['catcherMaxSize'],
            "allowFiles" => $this->CONFIG['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName = $this->CONFIG['catcherFieldName'];

        /* 抓取远程图片 */
        $list = array();
        if (isset($_POST[$fieldName])) {
            $source = $_POST[$fieldName];
        } else {
            $source = $_GET[$fieldName];
        }
        if (is_array($source)) {
            foreach ($source as $imgUrl) {
                $item = new UeditorUploader($imgUrl, $config, "remote");
                $item->setFolder($this->folder);
                $item->upload();
                $info = $item->getFileInfo();
                array_push($list, array(
                    "state" => $info["state"],
                    "url" => $info["url"] . $this->show_image_suffix,
                    "size" => $info["size"],
                    "title" => htmlspecialchars($info["title"]),
                    "original" => htmlspecialchars($info["original"]),
                    "source" => htmlspecialchars($imgUrl)
                ));
            }
        }
        /* 返回抓取数据 */
        return json_encode(array(
            'state' => count($list) ? 'SUCCESS' : 'ERROR',
            'list' => $list
        ));
    }

    /**
     * 文件上传
     * @return string
     */
    protected function upload()
    {
        /* 上传配置 */
        $base64 = "upload";
        switch (htmlspecialchars($_GET['action'])) {
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $this->CONFIG['imagePathFormat'],
                    "maxSize" => $this->CONFIG['imageMaxSize'],
                    "allowFiles" => $this->CONFIG['imageAllowFiles']
                );
                $fieldName = $this->CONFIG['imageFieldName'];
                break;
            case 'uploadscrawl':
                $config = array(
                    "pathFormat" => $this->CONFIG['scrawlPathFormat'],
                    "maxSize" => $this->CONFIG['scrawlMaxSize'],
                    "allowFiles" => $this->CONFIG['scrawlAllowFiles'],
                    "oriName" => "scrawl.png"
                );
                $fieldName = $this->CONFIG['scrawlFieldName'];
                $base64 = "base64";
                break;
            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $this->CONFIG['videoPathFormat'],
                    "maxSize" => $this->CONFIG['videoMaxSize'],
                    "allowFiles" => $this->CONFIG['videoAllowFiles']
                );
                $fieldName = $this->CONFIG['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $config = array(
                    "pathFormat" => $this->CONFIG['filePathFormat'],
                    "maxSize" => $this->CONFIG['fileMaxSize'],
                    "allowFiles" => $this->CONFIG['fileAllowFiles']
                );
                $fieldName = $this->CONFIG['fileFieldName'];
                break;
        }
        /* 生成上传实例对象并完成上传 */
        $up = new UeditorUploader($fieldName, $config, $base64);
        $up->setFolder($this->folder);
        $up->upload();

        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
         */
        /* 返回数据 */
        $file_info = $up->getFileInfo();
        if (htmlspecialchars($_GET['action']) == 'uploadimage') {
            $file_info['url'] .= $this->show_image_suffix;
        }
        return json_encode($file_info);
    }
}
